<template>
    <div class="">
        <Breadcrumb :route="routes" />
        <div class="wb-container">
            <div class="mian-content">
                <formPage :options="options" :fromList="formList" @submit="handleBaseSubmit" @reset="handleResetFun"
                    v-if="isFormShow" />
                <Action :options="option" @addClick="handleAddFun" @souauoClcik="isFormShow = !isFormShow"
                    @removeClick="handelRemoveFun" @loadClick="handelLoadClick"></Action>
                <div class="table">
                    <el-table v-loading="loading" element-loading-text="加载数据..." :data="ManageData"
                        style="width: 100%;height: 100%;" size="small" border @selection-change="handleSelectionChange"
                        :header-cell-style="{ background: '#3CB731', color: '#fff', fontSize: '14px', height: '40px', letterSpacing: '2px' }">
                        <template #empty>
                            <el-empty description="暂无数据！" />
                        </template>
                        <el-table-column type="selection" width="55" align="center" />
                        <el-table-column prop="id" label="ID" align="center" />
                        <el-table-column prop="account" label="用户名" width="200" align="center" />
                        <el-table-column label="角色名称" width="200" align="center">
                            <template #default="{ row }">
                                <div>
                                    <el-tag style="margin-left: 6px;" v-for="item in row.admin_user_role">{{ item?.name
                                    }}</el-tag>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="last_login_time_at" label="上次登录时间" width="200" align="center" />
                        <el-table-column prop="created_at" label="开始时间" width="200" align="center" />
                        <el-table-column prop="updated_at" label="更新时间" width="200" align="center" />
                        <el-table-column prop="type" label="视觉/称重" width="200" align="center">
                            <template #default="{ row }">
                                <el-tag v-if="row.type === 1">称重板</el-tag>
                                <el-tag type="warning" v-if="row.type === 2">视觉板</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" align="center" min-width="300" class="right-button">
                            <template #default="{ row }">
                                <div class="tabel-btn">
                                    <el-button class="size" type="success" @click="handleClick(row)" v-has="'assignRole'">
                                        分配角色
                                    </el-button>
                                    <el-button class="size" type="info" @click="editClick(row)" v-has="'editAdmin'">
                                        编辑
                                    </el-button>
                                    <el-button class="size" type="danger" @click="removeClick(row)" v-has="'removeAdmin'">
                                        删除
                                    </el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>

            <!-- 分配管理员权限 -->
            <el-dialog v-model="dialogFormVisible" title="分配角色" width="45%">
                <el-table ref="perssionsTable" :data="list.rolIdList" @selection-change="handelChange">
                    <el-table-column type="selection" align="center" />
                    <el-table-column property="admin_user_id" label="用户ID" align="center" />
                    <el-table-column property="id" label="ID" align="center" />
                    <el-table-column property="name" label="角色名称" align="center" />
                </el-table>
                <div class="table-btn">
                    <el-button type="primary" @click="managePower()">确定</el-button>
                    <el-button @click="cancelClick()">取消</el-button>
                </div>
            </el-dialog>
            <el-dialog v-model="dialogFormAdd" title="添加管理员" width="30%">
                <el-form :model="list.formLabelAlign" :rules="rules" ref="formAdd" label-width="100">
                    <el-form-item label="用户名:" prop="account">
                        <el-input v-model="list.formLabelAlign.account" placeholder="可输入为纯数字，字母，也可以为数字和字母组成" />
                    </el-form-item>
                    <el-form-item label="密码:" prop="password">
                        <el-input type="password" v-model="list.formLabelAlign.password"
                            placeholder="输入1-10位数字,可以为数字和字母以及小数点的组成" />
                    </el-form-item>
                    <el-form-item label="确认密码:" prop="confirmPassword">
                        <el-input type="password" v-model="list.formLabelAlign.confirmPassword" placeholder="确认密码" />
                    </el-form-item>
                    <el-form-item label="类型:" prop="type" style="align-items: center;">
                        <el-radio-group v-model="list.formLabelAlign.type">
                            <el-radio label="1" size="large">称重板</el-radio>
                            <el-radio label="2" size="large">视觉板</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="resetForm(formAdd)">取消</el-button>
                        <el-button type="primary" @click="submitForm(formAdd)">提交</el-button>
                    </span>
                </template>
            </el-dialog>
            <el-dialog v-model="detaliData" title="修改密码" width="30%">
                <el-form :model="list.managaFormDetali" ref="formDetali" :rules="rules2" label-width="100">
                    <el-form-item label="密码:" prop="password">
                        <el-input v-model="list.managaFormDetali.password" type="password"
                            placeholder="输入1-10位数字,可以为数字和字母以及小数点的组成" />
                    </el-form-item>
                    <el-form-item label="确认新密码:" prop="confirmPassword">
                        <el-input v-model="list.managaFormDetali.confirmPassword" type="password" placeholder="确认新的密码" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="clearClick(formDetali)">取消</el-button>
                        <el-button type="primary" @click="detaliSubmit(formDetali)">
                            确定
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive, onBeforeMount } from "vue";
import { useRoute } from "vue-router";
import Breadcrumb from '@/components/nav-header'
import formPage from "@/components/form";
import Action from "@/components/action";
import { ElTable, ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { manageList, manageRole, manageAdd, manageRemove, manageEdit } from '../../api/manage'
import { roleList } from '@/api/role/index'
const route = useRoute()
const routes = ref()
const dialogFormVisible = ref(false)
//管理员ID
const manageId = ref()
//角色ID
const rloeId = ref(null)

const formAdd = ref()
const dialogFormAdd = ref(false)
const detaliData = ref(false)
const formDetali = ref()
const ManageData = ref([])
const isShow = ref(false)
const loading = ref(true)
const roleLists = ref([])
const list = reactive({
    formLabelAlign: {
        account: '',
        password: '',
        type: '1'
    },
    managaFormDetali: {
        password: '',
        confirmPassword: ''
    },
    roleName: '',
    searchVal: {
        role_id: ''
    }
})
const perssionsTable = ref()
const rules = reactive({
    account: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { pattern: '^[0-9a-zA-Z.]{1,}$', message: '可以为纯数字，字母，也可以为数字和字母组合' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { pattern: '^[0-9a-zA-Z.]{1,10}$', message: '输入1-10位，数字/字母/数字和字母以及小数点的任意组合' }
    ],
    confirmPassword: [
        { required: true, message: '请输入确认密码', trigger: 'blur' },
    ],
})
const rules2 = reactive({
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { pattern: '^[0-9a-zA-Z.]{1,10}$', message: '输入1-10位，数字/字母/数字和字母以及小数点的任意组合' }
    ],
    confirmPassword: [
        { required: true, message: '请输入确认密码', trigger: 'blur' },
    ],
})

//form表单的数据
const isFormShow = ref(false)
const multipleSelection = ref({})
const formList = reactive([
    {
        label: '角色名称',
        type: 'select',
        field: "role_id",
        placeholder: "选择角色",
    }
])
const options = reactive({
    showResetButton: true,
})
const option = reactive({
    shuaxinDisplay: true,
    addDisplay: true,
    editDiaplay: false,
    removeDisplay: true,
    caozuoDisplay: false,
    qiehuanDisplay: false,
    sousuoDisplay: true,
    disabled: true
})
const handleBaseSubmit = (value) => {
    list.searchVal.role_id = value.role_id
    getManageData()
}
const handleResetFun = (model) => {
    list.searchVal.role_id = model.role_id || ''
    getManageData()
}
const handleAddFun = () => {
    dialogFormAdd.value = true
}
const handelRemoveFun = () => {
    ElMessageBox.confirm(
        '确定要删除数据吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            for (let i = 0; i < multipleSelection.value.length; i++) {
                try {
                    simulation(multipleSelection.value[i])
                } catch (err) {
                    // console.log(err);
                }
            }
            option.disabled = true
        })
        .catch(() => {

        })
}
const handelLoadClick = () => {
    console.log('加载');
    getManageData()
}
const simulation = async (select) => {
    await manageRemove(select.id).then(res => {
        const { code, data } = res
        if (code == 200) {
            getManageData()
        }
    })
}
//表格选择数据
const handleSelectionChange = (val) => {
    multipleSelection.value = val
    if (multipleSelection.value.length > 0) {
        option.disabled = false
    } else {
        option.disabled = true
    }
}
onBeforeMount(async () => {
    await roleList().then(e => {
        const { code, data } = e
        if (code == 200) {
            let roleId = []
            for (let j = 0; j < data.data.length; j++) {
                roleId.push({
                    label: data.data[j].name,
                    value: data.data[j].id
                })
            }
            formList.forEach(item => {
                if (item.label == '角色名称') {
                    item.option = roleId
                }
            })
        }
    })
})
onMounted(() => {
    routes.value = route.matched
    getManageData()
})
//请求管理员列表
const getManageData = async () => {
    // list.searchVal.role_id = list.roleName
    const managaData = await manageList(list.searchVal).then(r => {
        const { code, data } = r
        console.log(data, '管理员列表');
        loading.value = false
        if (code == 200) {
            if (Object.keys(data).length == 0) {
                ManageData.value = []
                isShow.value = true
            } else {
                ManageData.value = data
                isShow.value = false
            }
        }
    }).catch((err) => {
        loading.value = false
    })
}
//点击分配权限按钮的回调
const handleClick = (row) => {
    manageId.value = row.id
    roleLists.value = row.admin_user_role
    dialogFormVisible.value = true
}
const handelChange = (...args) => {
    for (let item of args) {
        const it = item.map(it => (
            it.id
        ))
        const selectData = [...it]
        rloeId.value = selectData
    }
    const id = Object.values(rloeId.value)
    return id
}
//调接口为管理员分配权限
const managePower = async () => {
    let roleIds = handelChange()
    const power = await manageRole({ id: manageId.value, role_ids: roleIds }).then(res => {
        const { code, data } = res
        if (code == 200) {
            ElMessage.success('角色分配成功')
            dialogFormVisible.value = false
            getManageData()
            perssionsTable.value.clearSelection()
        }
    })
}
// 取消选择
const cancelClick = () => {
    dialogFormVisible.value = false
    perssionsTable.value.clearSelection()
}

//添加管理员
const AddClick = () => {
    dialogFormAdd.value = true
}

const submitForm = (formEl) => {
    if (!formEl) return
    if (list.formLabelAlign.password === list.formLabelAlign.confirmPassword) {
        formEl.validate(async (valid) => {
            if (valid) {
                const add = await manageAdd({
                    account: list.formLabelAlign.account,
                    password: list.formLabelAlign.password,
                    type: list.formLabelAlign.type
                }).then(result => {
                    const { code, data } = result
                    if (code == 200) {
                        ElMessage.success('管理员添加成功')
                        formEl.resetFields()
                        getManageData()
                        dialogFormAdd.value = false
                    }
                })
            } else {
                ElMessage.warning('密码或者用户名必填')
                return false
            }
        })
    } else {
        ElMessage.error('两次密码输入不一致，请重新输入')
    }

}
const clearClick = (formElement) => {
    if (!formElement) return
    formElement.resetFields()
    detaliData.value = false
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    dialogFormAdd.value = false
}

//删除管理员
const removeClick = async (row) => {
    ElMessageBox.confirm(
        '确定要删除这条数据吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let removeId = row.id
            const remove = await manageRemove(removeId)
            const { code, data } = remove
            if (code == 200) {
                ElMessage({
                    type: 'success',
                    message: '删除成功',
                })
                getManageData()
            }
        })
        .catch(() => {

        })
}

const id = ref()
const editClick = (row) => {
    id.value = row.id
    detaliData.value = true
}

const detaliSubmit = (Elform) => {
    if (!Elform) return
    if (list.managaFormDetali.password === list.managaFormDetali.confirmPassword) {
        Elform.validate(async (valid) => {
            if (valid) {
                const edit = await manageEdit(id.value, { password: list.managaFormDetali.password })
                const { code, data } = edit
                if (code == 200) {
                    ElMessage.success('编辑密码成功')
                    list.managaFormDetali = {}
                } else {
                    ElMessage.error('编辑密码失败')
                }
                detaliData.value = false
            } else {
                ElMessage.warning('密码必须填写')
                return false
            }
        })
    } else {
        ElMessage.error('两次密码输入不一致，请重新输入')
    }
}
const searchRoleClick = () => {
    getManageData()
}

</script>

<style lang="less" scoped>
.mian-search {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
        padding: 10px 0 20px 0;
    }

    .header-right {
        display: flex;
        flex-direction: row;

        .el-input {
            width: 300px;
        }
    }

    .header-left button {
        margin-right: 2px;
    }

    .header-right .xlsx {
        padding: 10px;
        background-color: #ddd;
        margin-left: 5px;
        border: 1px solid #dddddd;
        border-radius: 5px;
    }

    .right-button .el-tooltip .el-button {
        margin-left: 10px
    }

}

.dialog-footer button:first-child {
    margin-right: 10px;
}

.dialog-footer {
    .el-button {
        padding: 4px 20px;
        font-size: 14px;
    }
}

.el-dialog__header {
    text-align: center;
}

.table-btn {
    padding: 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

:deep(.el-dialog) {
    header {
        background: rgb(68, 171, 247);
        margin-right: 0;

        .el-dialog__title {
            color: #fff;
        }

        .el-dialog__headerbtn i {
            color: #fff;
        }
    }
}

:deep(.el-dialog__close) {
    color: #fff;
}

:deep(.el-button) {
    padding: 2px 10px;
    font-size: 12px;
    letter-spacing: 2px;
}

.emptyText {
    font-size: 16px;
    margin-top: 20px;
}

.size {
    font-size: 12px;
    margin: 0 10px;
}

.tabel-btn {
    margin: 10px;
}
</style>
